<template>
  <div style="margin-top: 10px">
    <el-card>
      <el-form :label-position="labelPosition" label-width="100px" style="max-width: 100%">
        <el-form-item label="SKU名称">
          <el-input v-model="SkuForm.skuName" />
        </el-form-item>

        <el-form-item label="价格">
          <el-input v-model="SkuForm.price" type="number" />
        </el-form-item>

        <el-form-item label="重量">
          <el-input v-model="SkuForm.weight" type="number" />
        </el-form-item>

        <el-form-item label="SKU描述">
          <el-input v-model="SkuForm.skuDesc" type="textarea" />
        </el-form-item>

        <el-form-item label="平台属性">
          <el-form inline>
            <el-form-item v-for="item in attrArr" :label="item.attrName" :key="item.id">
              <el-select v-model="item.attrIdAndValueId" placeholder="请选择平台属性">
                <el-option v-for="i2 in item.attrValueList" :key="i2.id" :label="i2.valueName" :value="`${item.id}:${i2.id}`" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="销售属性">
          <el-form inline>
            <el-form-item v-for="item in saleArr" :key="item.id" :label="item.saleAttrName">
              <el-select v-model="item.saleIdAndValueId" placeholder="请选择销售属性">
                <el-option v-for="i2 in item.spuSaleAttrValueList" :label="i2.saleAttrValueName" :value="`${item.id}:${i2.id}`" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="图片名称">
          <el-table ref="multipleTableRef" :data="imgArr" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <img :src="row.imgUrl" alt="" style="width: 100px; height: 100px" />
              </template>
            </el-table-column>
            <el-table-column property="imgName" label="名称" width="120" />
            <el-table-column label="操作">
              <template #="{ $index }">
                <el-button type="primary" size="small" @click="toggleSelection($index)">设为默认</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="save($parent)">保存</el-button>
          <el-button type="danger" @click="cancel($parent)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormProps } from 'element-plus'
import { SaleAttr, SpuImg, SpuData } from '@/utils/api/product/spu/type'
import { Attr } from '@/utils/api/product/attr/type'
import { ElTable } from 'element-plus'
import { reqAttr } from '@/utils/api/product/attr'
import { useCategoryStore } from '@/store/module/category'
import { reqSpuHasSaleAttr, reqSpuImageList, reqAddSku } from '@/utils/api/product/spu'

const categoryStore = useCategoryStore()

const labelPosition = ref<FormProps['labelPosition']>('right')

const SkuForm = reactive({
  category3Id: '',
  tmId: 0,
  spuId: 0,
  skuName: '',
  price: '',
  weight: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: ''
})
// 平台属性
const attrArr = ref<Attr[]>([])
// 销售属性
const saleArr = ref<SaleAttr[]>([])
// 图片列表
const imgArr = ref<SpuImg[]>([])

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
// const multipleSelection = ref<SpuImg[]>([])

// 处理选中的图片
const handleSelectionChange = (val: SpuImg[]) => {
  SkuForm.skuDefaultImg = val[0].imgUrl!
}

// 获取平台属性
const getAttr = async () => {
  const res = await reqAttr(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id)
  attrArr.value = res.data.data
}

// 获取销售属性数据
const getSkuData = async (spuId: number) => {
  const res = await reqSpuHasSaleAttr(spuId)
  saleArr.value = res.data.data
}

// 获取图片
const getImgList = async (spuId: number) => {
  const res = await reqSpuImageList(spuId)
  imgArr.value = res.data.data
}

// 父组件调用初始化
const initData = (row: SpuData) => {
  SkuForm.category3Id = categoryStore.c3Id
  SkuForm.spuId = row.id!
  SkuForm.tmId = row.tmId as number

  getAttr()
  getSkuData(row.id!)
  getImgList(row.id!)
}

// 点击设为默认按钮
const toggleSelection = (index: number) => {
  multipleTableRef.value!.clearSelection()
  // @ts-expect-error
  multipleTableRef.value!.toggleRowSelection(imgArr.value[index], undefined)
}

// 保存按钮
const save = async ($parent: any) => {
  // 对平台属性进行过滤
  let attrFilter = attrArr.value.filter((item: Attr) => {
    return item.attrIdAndValueId
  })

  SkuForm.skuAttrValueList = attrFilter.map((item: Attr) => {
    if (item.attrIdAndValueId) {
      let arr = item.attrIdAndValueId.split(':')
      return {
        attrId: arr[0],
        valueId: arr[1]
      }
    }
  }) as any

  // 对销售属性过滤
  let saleFilter = saleArr.value.filter((item: SaleAttr) => {
    return item.saleIdAndValueId
  })

  SkuForm.skuSaleAttrValueList = saleFilter.map((item: SaleAttr) => {
    if (item.saleIdAndValueId) {
      let arr = item.saleIdAndValueId.split(':')
      return {
        saleAttrId: arr[0],
        saleAttrValueId: arr[1]
      }
    }
  }) as any

  const res = await reqAddSku(SkuForm)
  if (res.data.code == 200) {
    ElMessage.success('新增SKU成功')
    $parent.$parent.change_is_show_add()
    $parent.$parent.getSpu()
  }
}

// 点击取消按钮
const cancel = ($parent: any) => {
  $parent.$parent.change_is_show_add()
  $parent.$parent.getSpu()
}

defineExpose({ initData })
</script>

<style scoped></style>
